package com.xywy.find;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.util.FileUtil;
import com.xywy.common.widget.zrcListView.SimpleFooter;
import com.xywy.common.widget.zrcListView.SimpleHeader;
import com.xywy.common.widget.zrcListView.ZrcListView;
import com.xywy.common.widget.zrcListView.ZrcListView.OnStartListener;
import com.xywy.find.adapter.NewJkgcAdapter;
import com.xywy.find.bean.JkgcData;
import com.xywy.find.bean.NewJkgcBig;
import com.xywy.find.bean.NewJkgcItem;
import com.xywy.find.paser.JkgcPaser;
import com.xywy.me.bean.UserKeeper;

/**
 * 健康广场
 * 
 * @author yangyu
 */
public class JkgcPlazeFragment extends Fragment {
	private TextView tv;
	private ZrcListView lv;
	private List<JkgcData> jkgcList;

	private List<NewJkgcItem> njkgcList;
	private NewJkgcAdapter jkgcAdapter;

	private int currentPage = 0;
	private String currentTitle = null;
	private String currentTarget = null;
	private String userid;
	private boolean isAlive = true;

	// MyProgress myProgress;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// myProgress.stop();
			switch (msg.what) {
			case JkgcPaser.SUCCESS:
				String result = (String) msg.obj;
				if (isAlive)
					getServerList(result);
				break;
			case JkgcPaser.FAILURE:
				Toast.makeText(getActivity(), getString(R.string.common_net_fail), Toast.LENGTH_SHORT).show();
				getFromLocal();
				break;
			}
		}

	};

	// 处理从服务器上获取的数据
	private void getServerList(String result) {
		String data = null;
		JSONObject jsonObject = null;
		try {
			if (null == result || TextUtils.isEmpty(result)) {
				Toast.makeText(getActivity(), "获取返回结果为空", Toast.LENGTH_LONG)
						.show();
				lv.setRefreshFail("加载失败");
				getFromLocal();
				return;
			}
			jsonObject = new JSONObject(result);
			data = jsonObject.getString("data");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if (null == data) {
			return;
		}
		Gson gson = new Gson();
		java.lang.reflect.Type type = new TypeToken<List<NewJkgcItem>>() {
		}.getType();
		njkgcList = gson.fromJson(data, type);
		String big = null;
		if (currentPage >= 2) {
			addServerAdapter(njkgcList);
			if (currentPage < 4) {
				List<NewJkgcItem> list = FileUtil.getList(userid + "jkgcList"
						+ currentTarget);
				list.addAll(njkgcList);
				FileUtil.saveObject(userid + "jkgcList" + currentTarget, list);
			}
		} else {
			try {
				big = jsonObject.getString("big");
				NewJkgcBig bigData = gson.fromJson(big, NewJkgcBig.class);
				setServerAdapter(njkgcList, bigData);
				// 下拉刷新成功 这个时候要把数据清除 然后 添加到文件中
				FileUtil.clearFile(userid + "jkgcListBig" + currentTarget);
				FileUtil.saveObject(userid + "jkgcListBig" + currentTarget,
						bigData);
				FileUtil.clearFile(userid + "jkgcList" + currentTarget);
				FileUtil.saveObject(userid + "jkgcList" + currentTarget,
						njkgcList);
			} catch (JSONException e) {
				addServerAdapter(njkgcList);
				e.printStackTrace();
			}
		}

	}

	private void getFromLocal() {
		njkgcList = (List<NewJkgcItem>) FileUtil.getObject(userid + "jkgcList"
				+ currentTarget);
		NewJkgcBig bigData = (NewJkgcBig) FileUtil.getObject(userid
				+ "jkgcListBig" + currentTarget);
		if (njkgcList != null && bigData != null)
			setServerAdapter(njkgcList, bigData);
	};

	// 增加数据到当前显示集
	private void addServerAdapter(List<NewJkgcItem> njkgcList) {
		if (null == njkgcList) {
			lv.stopLoadMore();
			return;
		}
		jkgcAdapter.addListData(njkgcList);
		jkgcAdapter.notifyDataSetChanged();
		if (njkgcList.size() == 19) {
			lv.setLoadMoreSuccess();
			if (currentPage == 1) {
				lv.setRefreshSuccess("加载成功"); // 通知加载成功
			}
		} else {
			Toast.makeText(getActivity(), "已经加载到最后一页！", Toast.LENGTH_LONG)
					.show();
			lv.stopLoadMore();
		}

	}

	// 将数据适配到List上
	private void setServerAdapter(List<NewJkgcItem> njkgcList,
			NewJkgcBig bigData) {

		jkgcAdapter.setListData(njkgcList);
		jkgcAdapter.setBigData(bigData);
		jkgcAdapter.notifyDataSetChanged();
		lv.setRefreshSuccess("加载成功"); // 通知加载成功
		lv.startLoadMore(); // 开启LoadingMore功能

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View contextView = inflater.inflate(R.layout.find_jkgc_fragment,
				container, false);

		this.initView(contextView);
		SharedPreferences sp = getActivity().getSharedPreferences("config",
				Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
        userid = UserKeeper.getCurrentUser(getActivity()).getUserid();
		return contextView;
	}

	private void initView(View contextView) {

		lv = (ZrcListView) contextView.findViewById(R.id.lv_jkgc_item);
		jkgcAdapter = new NewJkgcAdapter(getActivity());
		lv.setAdapter(jkgcAdapter);
		tv = (TextView) contextView.findViewById(R.id.tv);
		// 获取Activity传递过来的参数s
		Bundle mBundle = getArguments();
		currentTarget = mBundle.getString("target");
		currentTitle = mBundle.getString("title");
		tv.setText(currentTitle);

		lvOption();

	}

	/**
	 * 从服务器上行获取数据。
	 * 
	 * @param target
	 *            当前页面
	 */
	private void getServerInfo(String target) {
		// myProgress = new MyProgress(getActivity(), 10);
		// myProgress.start();
		JkgcPaser paser = new JkgcPaser(getActivity(), handler);
		paser.sendMsg(target, currentPage + "");
	}

	private void lvOption() {
		// 设置默认偏移量，主要用于实现透明标题栏功能。（可选）
		float density = getResources().getDisplayMetrics().density;
		// lv.setFirstTopOffset((int) (0 * density));

		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(getActivity());
		header.setTextColor(0xff666666);
		header.setCircleColor(0xff1fb5ad);
		lv.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(getActivity());
		footer.setCircleColor(0xff1fb5ad);
		lv.setFootable(footer);

		// 设置列表项出现动画（可选）
		lv.setItemAnimForTopIn(R.anim.topitem_in);
		lv.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 下拉刷新事件回调（可选）
		lv.setOnRefreshStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				currentPage = 1;
				refresh();
			}
		});

		// 加载更多事件回调（可选）
		lv.setOnLoadMoreStartListener(new OnStartListener() {
			@Override
			public void onStart() {
				currentPage++;
				loadMore();
			}
		});
		lv.refresh(); // 主动下拉刷新

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	private void refresh() {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (!isAlive)
					return;
				jkgcAdapter.setCurrentTarget(currentTarget);
				jkgcAdapter.setCurrentTitle(currentTitle);
				getServerInfo(currentTarget);
			}
		}, 1 * 1000);
	}

	private void loadMore() {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (!isAlive)
					return;
				if (currentPage < 2) {
					Toast.makeText(getActivity(), " request page error",
							Toast.LENGTH_LONG).show();
				} else {
					getServerInfo(currentTarget);
				}

			}
		}, 1 * 1000);
	}

	@Override
	public void onDetach() {
		super.onDetach();
		try {
			Field childFragmentManager = Fragment.class
					.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);

		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		isAlive = false;
		super.onDestroy();
	}
}